import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus';
import router from './router/index';

let loading;

const startLoading = () => {
    loading = ElLoading.service({
        lock: true,
        text: '努力加载中',
        background: 'rgba(0,0,0,.7)'
    });
};

const endLoading = () => {
    loading.close();
};

// 配置请求拦截器
axios.interceptors.request.use(
    config => {
        startLoading();
        if (localStorage.mytoken) {
            config.headers.Authorization = localStorage.mytoken;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 配置响应拦截器
axios.interceptors.response.use(
    response => {
        endLoading();
        return response;
    },
    error => {
        endLoading();
        ElMessage.error(error.response.data);

        const { status } = error.response;
        if (status === 401) {
            ElMessage.error('token失败，请重新登陆！');
            localStorage.removeItem('mytoken');
            router.push('/login');
        }
        return Promise.reject(error);
    }
);

export default axios;
